package com.videohigh.updatelib;

import android.util.Log;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class SilentInstallUtils {

    public static boolean installBySilent(String apkPath, String packageName) {

        Log.d("SilentInstall", " in installBySilent: ");

        Process process = null;
        BufferedReader successResult = null;
        BufferedReader errorResult = null;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder errorMsg = new StringBuilder();
        try {
            process = new ProcessBuilder("pm", "install", "-i", packageName, "-r", apkPath).start();
            successResult = new BufferedReader(new InputStreamReader(process.getInputStream()));
            errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            String s;
            while ((s = successResult.readLine()) != null) {
                successMsg.append(s);
            }
            while ((s = errorResult.readLine()) != null) {
                errorMsg.append(s);
            }
        } catch (Exception e) {
            Log.e("SilentInstall", "Exception: " + e);
        } finally {
            try {
                if (successResult != null) {
                    successResult.close();
                }
                if (errorResult != null) {
                    errorResult.close();
                }
            } catch (Exception e) {

            }
            if (process != null) {
                process.destroy();
            }
        }
        Log.e("SilentInstall", "errorMsg " + errorMsg.toString());
        //如果含有“success”认为安装成功
        return successMsg.toString().equalsIgnoreCase("success");

    }
}